'use client'

import { useEffect, useState } from "react";
import { DrawInfo, ShareInfo } from "@/grpc/types";
import { createTLStore, Tldraw } from "tldraw";
import 'tldraw/tldraw.css';

export interface DrawPanelProps {
    shareInfo: ShareInfo;
}

export function DrawPanel(props: DrawPanelProps) {
    const [contentStore] = useState(createTLStore());
    const [errorMsg, setErrorMsg] = useState("");

    const loadDrawContent = async () => {
        const res = await fetch(`/api/draw?id=${props.shareInfo.shareId}&secret=${props.shareInfo.shareSecret}`);
        const resData = await res.json() as {
            code: number;
            errMsg: string;
            info: DrawInfo;
        };
        if (resData.code == 0) {
            const data = JSON.parse(resData.info.content ?? "");
            contentStore.loadStoreSnapshot(data);
        } else {
            setErrorMsg(resData.errMsg);
        }
    };

    useEffect(() => {
        loadDrawContent();
    }, []);

    return (
        <>
            {errorMsg != "" && errorMsg}
            {errorMsg == "" && (
                <div style={{ height: "100vh", width: "100vw" }}>
                    <Tldraw store={contentStore}
                        components={{
                            ContextMenu: null,
                            MainMenu: null,
                            SharePanel: null,
                            CursorChatBubble: null,
                        }}
                        onMount={(newEditor) => {
                            newEditor.updateInstanceState({ isReadonly: true });
                            newEditor.user.updateUserPreferences({
                                locale: "zh-cn",
                            });
                            setTimeout(() => {
                                newEditor.updateInstanceState({ isReadonly: true });
                                newEditor.user.updateUserPreferences({
                                    locale: "zh-cn",
                                });
                            }, 200);
                        }} />
                </div>

            )}
        </>
    );
}